package com.yxx.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxx.mapper.EmployeeMapper;
import com.yxx.medicinecommon.constant.MessageConstant;
import com.yxx.medicinecommon.constant.PasswordConstant;
import com.yxx.medicinecommon.constant.StatusConstant;
import com.yxx.medicinecommon.context.BaseContext;
import com.yxx.medicinecommon.exception.AccountLockedException;
import com.yxx.medicinecommon.exception.AccountNotFoundException;
import com.yxx.medicinecommon.exception.PasswordErrorException;
import com.yxx.medicinecommon.result.PageResult;
import com.yxx.medicinepojo.dto.EmployeeDTO;
import com.yxx.medicinepojo.dto.EmployeeLoginDTO;
import com.yxx.medicinepojo.dto.EmployeePageQueryDTO;
import com.yxx.medicinepojo.dto.PasswordEditDTO;
import com.yxx.medicinepojo.entity.Employee;
import com.yxx.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 员工管理
 * @author yuxiangxun
 * @date 2024/9/5
 * @apiNote
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询：select * from employee limit 0, 10 (左开右闭) 一页十条数据
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());

        Page<Employee> employeeList = employeeMapper.pageQuery(employeePageQueryDTO);
        PageResult pageResult = new PageResult();
        pageResult.setRecords(employeeList.getResult());
        pageResult.setTotal(employeeList.getTotal());
        return pageResult;
    }

    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (StatusConstant.DISABLE.equals(employee.getStatus())) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 员工的启用/禁用
     * @param status
     * @param id
     */
    @Override
    public void enable_disable_status(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();

        //根据employee对象进行更新（启用禁用）操作
        employeeMapper.update(employee);
    }

    /**
     * 插入员工信息
     * @param employeeDTO
     */
    @Override
    public void insert(EmployeeDTO employeeDTO) {
        //通过线程获取当前用户id
        long user_id = Thread.currentThread().getId();

        //创建新的Employee对象
        Employee employee = new Employee();

        //对象拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

        //设置状态为1  1 正常   0 锁定
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码 默认123456  设置md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //通过Employee对象中的数据进行插入员工信息操作
        employeeMapper.insert(employee);

    }

    /**
     * 通过员工id查询员数据
     * @param id
     * @return
     */
    @Override
    public Employee select_Employee_id(Long id) {
        Employee employee = employeeMapper.select_Employee_id(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void update_Employee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employeeMapper.update(employee);
    }

    /**
     * 修改/更新密码
     * @param passwordEditDTO
     */
    @Override
    public void updateEmployeePassword(PasswordEditDTO passwordEditDTO) throws Exception{
        //根据当前线程id获取到当前用户id
        Long user_id = BaseContext.getCurrentId();

        //根据当前用户id获取到当前用户的信息
        Employee employee = employeeMapper.getByEmployeeId(user_id);

        //如果查询出来的employee 为空，抛出自定义异常，账号为空
        if (employee == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //提取passwordEditDTO中的旧密码进行md5加密 赋值给 oldPassword
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());

        //从数据库中拿到的当前用户已经md5加密的密码 和 oldPassword 比较，如果不相等，则抛出自定义异常,显示“密码修改失败”
        if(!oldPassword.equals(employee.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

        //如果相等，就从passwordEditDTO中获取到新密码，进行md5加密后，更新到数据库
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        employee.setPassword(newPassword);
        employeeMapper.update(employee);
    }
}
